#include "bit.h"
#include <string.h>

int donner_bit(const unsigned char *bits, int pos) {

    unsigned char masque;
    masque = 0x80; // 10000000
    int i;

    for(i = 0; i < (pos % 8); i++) {
        masque = masque >> 1; // décalage du masque
    }

    return (((masque & bits[(int)(pos / 8)]) == masque) ? 1 : 0);
}

void modif_bit(unsigned char *bits, int pos, int etat) {

    unsigned char masque;
    masque = 0x80; // 1000 0000
    int i;

    for(i = 0; i < (pos % 8); i++)
        masque = masque >> 1;

    if (etat)
        bits[pos / 8] = bits[pos / 8] | masque;
    else
        bits[pos / 8] = bits[pos / 8] & (~masque);

    return;


}

void xor_bit(const unsigned char *bits1, const unsigned char *bits2, unsigned char *bitsx, int taille) {

    int i;

    for(i = 0; i < taille; i++) {

        if(donner_bit(bits1, i) != donner_bit(bits2, i))
            modif_bit(bitsx, i, 1);
        else
            modif_bit(bitsx, i, 0);
    }

    return;

}

void bit_rot_gauche(unsigned char *bits, int taille, int nbre) {

    int fbit, lbit, i, j;

    if(taille > 0) {

        for(i = 0; i < nbre; i++) {
            for(j = 0; j <= ((taille - 1) / 8); j++) {

                lbit = donner_bit(&bits[j], 0);

                if(j == 0)
                    fbit = lbit;
                else
                    modif_bit(&bits[j - 1], 7, lbit);

                bits[j] = bits[j] << 1;

                }

            modif_bit(bits, taille - 1, fbit);
        }

    }

    return;
}
